<?php
/**
 * quick_curd
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: 2025/1/15
 * 描述:
 */

namespace app\service;


class CurdService
{

    public static $auto_increment_field = 'id';// 自增字段

    // 设置自增ID字段
    public static function set_auto_increment_field($field): void
    {
        self::$auto_increment_field = $field;
    }

    // 手动格式化数组为字符串
    static function arrayToString($array)
    {
        $space = '            ';
        $str = '[' . PHP_EOL . $space;
        foreach ($array as $value) {
            $tmp = '[';
            foreach ($value as $k => $v) {
                if (is_array($v)) {
                    $tmp .= PHP_EOL . $space;
                    $tmp .= "'$k' => [";
                    foreach ($v as $v1) {
                        $tmp .= " [";
                        foreach ($v1 as $k2 => $v2) {
                            if (!is_array($v2)){
                                $tmp .= "'$k2' => '$v2',";
                            }else{
                                $tmp .= PHP_EOL . $space;
                                foreach ($v2 as $k3 => $v3) {
                                    $tmp .= "'$k3' => '$v3',";
                                }
                            }
                        }
                        $tmp .= '],';
                    }
                    $tmp .= ']';
                } else {
                    $tmp .= "'$k' => '$v',";
                }

            }
            $str .= $tmp . '],' . PHP_EOL . $space;
        }
        $str .= ']';
        return $str;
    }


    // 生成结果类，核心类
    static function tpl_result($args): string
    {
        $className = $args['className'];
        $modelName = $args['modelName'];
        $searchFields = $args['searchFields'] ?? [];
        $tableFields = $args['tableFields'] ?? [];
        $formFields = $args['formFields'] ?? [];
        $admin_apis = $args['admin_apis'] ?? [];
        $searchWhereStr = $args['searchWhereStr']?? '';
        $apis = $args['apis'] ?? [];
        $need_user_id = $args['need_user_id'];
        $tableFields = self::arrayToString($tableFields);
        $searchFields = self::arrayToString($searchFields);
        $formFields = self::arrayToString($formFields);
        $autoId = self::$auto_increment_field;
        $date = date('Y/m/d');
        $baseTpl = <<<doc
<?php
/**
 * quick_curd
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: $date
 * 描述: api_xxx 代表前端接口,其它代表后端接口
 */

namespace app\\result\\auto;

use app\\model\\auto\\$modelName;
use app\\result\\BaseResult;


class $className extends BaseResult
{
    public function __construct()
    {
        parent::__construct();
        \$this->model = new $modelName();
    }
doc;

        if (in_array('save_data', $admin_apis) || in_array('edit_data', $admin_apis)) {
            $baseTpl .= <<<doc


    // 保存数据
    public function save_data(\$args): array
    {
        \$formField = method_exists(\$this, 'form_fields') ? \$this->form_fields() : [];
        if (!\$formField) {
            return \$this->error_return('请先定义表单字段');
        }
        \$id = intval(\$args['id'] ?? 0);
        if (\$id) {
            \$data = \$this->model->data_get(['$autoId' => \$id]);
            if (!\$data) {
                return \$this->error_return('数据不存在');
            }
        }
        \$baseData = [];
        foreach (\$formField as \$field) {
            if (\$id) {
                if (\$field['isEditable']) {
                    if (\$field['isRequired'] && !\$args[\$field['field']]){
                        return \$this->error_return('缺少必填项：' . \$field['label']);
                    }
                    if (is_array(\$args[\$field['field']])){
                        \$args[\$field['field']] = implode(',', \$args[\$field['field']]);//默认用逗号分隔
                    }
                    \$baseData[\$field['field']] = \$args[\$field['field']] ?? \$data[\$field['field']];
                }
            } else {
                if (\$field['isRequired'] && !\$args[\$field['field']]){
                    return \$this->error_return('缺少必填项：' .\$field['label']);
                }
                if (is_array(\$args[\$field['field']])){
                    \$args[\$field['field']] = implode(',', \$args[\$field['field']]);//默认用逗号分隔
                }
                \$baseData[\$field['field']] = \$args[\$field['field']] ?? '';
            }
        }
        if (\$id) {
            \$this->model->data_update(['$autoId' => \$id], \$baseData);
        } else {
            \$this->model->data_add(\$baseData);
        }
        return \$this->success_return('保存成功');
    }
doc;
        }

        if ($formFields) {
            $baseTpl .= <<<doc


    // 表单字段
    public function form_fields(): array
    {
        return $formFields;
    }
doc;
        }

        if (in_array('list', $admin_apis)) {
            $baseTpl .= <<<doc

    //列表页面配置
    public function list_config(): array
    {
         return \$this->success_return('success', [
            'form_fields' => method_exists(\$this, 'form_fields') ? \$this->form_fields() : [],
            'el_table_column' => method_exists(\$this, 'el_table_column') ? \$this->el_table_column() : [],
            'search_fields' => method_exists(\$this, '_searchField') ? \$this->_searchField() : []
        ]);
    }

    // 表格列
    public function el_table_column(): array
    {
        return $tableFields;
    }

    //列表搜索字段
    private function _searchField(): array
    {
        return $searchFields;
    }

    // 获取公共条件限制
    private function _where(\$args = []): array
    {
        \$where = [];
        $searchWhereStr
        return \$where;
    }

    public function list(\$args = []): array
    {
        \$page = intval(\$args['page'] ?? 1);
        \$pageSize = intval(\$args['limit'] ?? 10);
        \$sort_by = trim(\$args['sort_by'] ?? '$autoId desc');
        \$where = \$this->_where(\$args);
        \$total = \$this->model->data_count(\$where);
        \$data = \$this->model->data_list(\$where, '*', \$sort_by, \$page, \$pageSize);
        return \$this->success_return('success', [
            'total' =>\$total,
            'list' => \$data,
        ]);
    }

doc;

        }

        if (in_array('get', $admin_apis)) {
            $baseTpl .= <<<doc


    // 获取详情
    public function get(\$args = []): array
    {
        \$id = intval(\$args['id'] ?? 0);
        \$data = \$this->model->data_get(["$autoId" => \$id]);
        if (!\$data) {
            return \$this->error_return('数据不存在');
        }
        return \$this->success_return('success', [
            'info' => \$data
        ]);
    }
doc;

        }

        if (in_array('status', $admin_apis)) {
            $baseTpl .= <<<doc


    //快速修改状态
    public function set_status(\$args): array
    {
        \$id = intval(\$args['id'] ?? 0);
        if (!\$id) {
            return \$this->error_return('参数错误');
        }
        \$data = \$this->model->data_get(["$autoId" => \$id], 'status');
        if (!\$data) {
            return \$this->error_return('数据不存在');
        }
        \$res = (new $modelName())->data_update(["$autoId" => \$id], ['status' => \$data['status'] == 1 ? -1 : 1]);
        if (!\$res) {
            return \$this->error_return('修改状态失败');
        }
        admin_log('修改状态', \$args);
        return \$this->success_return('保存成功');
    }
doc;

        }

        if (in_array('del_data', $admin_apis)) {
            $baseTpl .= <<<doc


    // 删除数据
    //todo 自己去写软删除还是硬删除
    public function del_data(\$args): array
    {
        \$ids = \$args['ids'] ?? [];
        if (!\$ids) {
            \$ids = !empty(\$args['id']) ? [\$args['id']] : [];
        }
        if (!\$ids) {
            return \$this->error_return('请选择数据');
        }
         \$data = \$this->model->data_list_nopage([["$autoId", 'in', \$ids]], '*');
        if (!\$data) {
            return \$this->error_return('数据不存在');
        }
        //判断是否存在del_time
        if (isset(\$data[0]['del_time'])) {
            \$res = \$this->model->data_update([["$autoId", 'in', \$ids]], ['del_time' => time()]);
        } else {
            \$res = \$this->model->data_del([["$autoId", 'in', \$ids]]);
        }
        if (!\$res) {
            return \$this->error_return('删除失败');
        }
        admin_log('删除客服数据', \$data);
        return \$this->success_return('删除成功');
    }
doc;

        }

        if (in_array('list_options', $admin_apis)) {
            $baseTpl .= <<<doc


    // 获取下拉列表
    public function list_options(\$args = []): array
    {
        \$all = \$this->model->data_list_nopage([
           // 'del_time' => 0,
           // 'status' => 1
        ], '*');
        if (\$all) {
            foreach (\$all as &\$item){
                \$item['label'] = \$item[''];//todo 自己改成对应的字段
                \$item['value'] = \$item['$autoId'];//todo 自己改成对应的字段
            }
        }
        return self::success_return('success', [
            'list' =>\$all,
        ]);
    }
doc;
        }
//------------------------------------------------------------
        //前端部分，用api_开头
        if (in_array('list', $apis)) {
            $baseTpl .= <<<doc

    // 获取列表
    public function api_list(\$args = []): array
    {
        \$page = max(\$args['page'] ?? 1, 1);
        \$page_size = max(\$args['page_size'] ?? 10, 1);
        if (\$page_size > 100) {
            \$page_size = 100;
        }
        \$where = [];
doc;
            if ($need_user_id){
                $baseTpl .= <<<doc

        \$user_id = intval(\$args['user_id']);
        if (!\$user_id) {
            return self::error_return('登录过期');
        }
        \$where[] =['user_id', '=', \$user_id];
doc;
            }

        $baseTpl .= <<<doc
        $searchWhereStr
        \$total = \$this->model->data_count(\$where);
        \$data = \$this->model->data_list(\$where, '*', '$autoId desc', \$page, \$page_size);
        if (\$data) {
            //todo 自己的逻辑
        }
       
        return self::success_return('success', [
            'total' => \$total,
            'list' => \$data,
        ]);
    }
doc;
        }
        if (in_array('detail', $apis)) {
            $baseTpl .= <<<doc


    //详情
    public function api_get(\$args = []): array
    {
        \$id = intval(\$args['$autoId'] ?? 0);
        if (!\$id) {
            return self::error_return('参数错误');
        }
        \$where = [
            ['$autoId', '=', \$id],
        ];
doc;
            if ($need_user_id){
                $baseTpl .= <<<doc

        \$user_id = intval(\$args['user_id']);
        if (!\$user_id) {
            return self::error_return('登录过期');
        }
         \$where[] = ['user_id', '=', \$user_id];
doc;
            }
            $baseTpl .= <<<doc

        \$data = \$this->model->data_get(\$where);
        if (!\$data) {
            return self::error_return('数据不存在');
        }
        
        return self::success_return('success', \$data);
    }
doc;
        }

        if (in_array('action', $apis)) {
            $baseTpl .= <<<doc

    //增改操作
    public function api_save_data( \$args = []): array
    {
        \$id = intval(\$args['$autoId'] ?? 0);
        \$where = [];
doc;
            if ($need_user_id){
                $baseTpl .= <<<doc

        \$user_id = intval(\$args['user_id']);
        if (!\$user_id) {
            return self::error_return('登录过期');
        }
        \$where[]= ['user_id', '=', \$user_id];
doc;
            }
            $baseTpl .= <<<doc

        if (\$id) {
            \$where[] = ['$autoId', '=', \$id];
            \$data = \$this->model->data_get(\$where);
            if (!\$data) {
                return self::error_return('数据不存在');
            }
        }

        \$rules = [
            //['name', 'empty|max:32', '请填写收货人姓名|收货人不能大于30个字'],
        ];
        /*\$check = check_param(\$args, \$rules);
        if (\$check['status'] != 0) {
            return self::error_return(\$check['msg']);
        }*/
        
        \$baseData = \$args;//fixme 自己判断
        
        if (\$id) {
            \$this->model->data_update(['$autoId' => \$id], \$baseData);
        } else {
            \$this->model->data_add(\$baseData);
        }
        return self::success_return('保存成功');
    }
doc;

        }

        if (in_array('remove', $apis)) {
            $baseTpl .= <<<doc

    
    //删除数据
    public function api_delete(\$args = []): array
    {
        \$id = intval(\$args['$autoId'] ?? 0);
        if (!\$id) {
            return self::error_return('参数错误');
        }
        \$where = [
            ['$autoId', '=', \$id],
        ];
doc;
            if ($need_user_id){
                $baseTpl .= <<<doc

        \$user_id = intval(\$args['user_id']);
        if (!\$user_id) {
            return self::error_return('登录过期');
        }
        \$where[]= ['user_id', '=', \$user_id];
doc;
            }
            $baseTpl .= <<<doc

        \$data = \$this->model->data_get(\$where);
        if (!\$data) {
            return self::error_return('数据不存在');
        }
        \$this->model->data_del(['$autoId' => \$id]);
        return self::success_return('操作成功');
    }
doc;

        }

        if (in_array('list_options', $apis)) {
            $baseTpl .= <<<doc


    //获取下拉列表
    public function api_list_options( \$args = []): array
    {
    
        \$where = [];
doc;


         if ($need_user_id){
                $baseTpl .= <<<doc

        \$user_id = intval(\$args['user_id']);
        if (!\$user_id) {
            return self::error_return('登录过期');
        }
        \$where[]= ['user_id', '=', \$user_id];
doc;
            }
         $baseTpl.=<<<doc

        \$all = \$this->model->data_list_nopage(\$where, '*');
        if (\$all) {
            foreach (\$all as &\$item){
                \$item['label'] = \$item[''];//fixme 自己改成对应的字段
                \$item['value'] = \$item['$autoId'];//todo 自己改成对应的字段
            }
        }
        return self::success_return('success', [
            'list' =>\$all,
        ]);
    }
doc;

        }

        if (in_array('setDefault', $apis)) {
            $baseTpl .= <<<doc


    //设置默认
    public function api_set_default(\$args = [])
    {
        \$id = intval(\$args['$autoId'] ?? 0);
        if (!\$id) {
            return self::error_return('参数错误');
        }
        \$where = [
            ['$autoId', '=', \$id],
        ];
doc;
            if ($need_user_id){
                $baseTpl .= <<<doc

        \$user_id = intval(\$args['user_id']);
        if (!\$user_id) {
            return self::error_return('登录过期');
        }
         \$where[]= ['user_id', '=', \$user_id];
doc;
            }
            $baseTpl .= <<<doc

        \$data = \$this->model->data_get(\$where);
        if (!\$data) {
            return self::error_return('数据不存在');
        }
        \$this->model->data_update(\$where, ['is_default' => 0]);
        \$this->model->data_update(['$autoId' => \$id], ['is_default' => 1]);
        return self::success_return('设置成功');
    }
doc;

        }


        $baseTpl .= <<<doc


}
doc;

        return $baseTpl;
    }


    //模型
    static function tpl_model($args): string
    {
        $modelName = $args['modelName'];
        $autoId = self::$auto_increment_field;
        $date = date('Y/m/d');
        $tpl = <<<doc
<?php
/**
 * quick_curd
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: $date
 * 描述:
 */

namespace app\model\auto;

use app\model\BaseModel;

class $modelName extends BaseModel
{
    protected \$autoinc="$autoId";
    protected \$pk = '$autoId';
    protected \$autoWriteTimestamp = true;
    protected \$createTime = 'created_at';
    protected \$updateTime = 'updated_at';
}
doc;
        return $tpl;
    }

    //管理后台控制器
    static function tpl_admin_controller($args): string
    {
        $date = date('Y/m/d');
        $className = $args['className'];
        $resultName = $args['resultName'];
        $tableName = $args['tableName'];
        $admin_apis = $args['admin_apis'] ?? [];
        $baseTpl = <<<doc
<?php
/**
 * quick_curd
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: $date
 * 描述:
 */

namespace app\\admin\\controller\\auto;

use app\\admin\\controller\\BaseAdmin;
use app\\admin\\controller\\BaseCurd;
use app\\result\\auto\\$resultName;
use think\App;

class $className extends BaseAdmin
{
    use BaseCurd;//引入增删改查

    public function __construct(App \$app)
    {
        parent::__construct(\$app);
        \$this->objResult = new $resultName();
    }
    
    public function index()
    {
        return \$this->view('$tableName/index');
    }
}

doc;
        return $baseTpl;

    }

    // 生成后台路由
    static function tpl_admin_route($args): string
    {
        $admin_apis = $args['admin_apis'] ?? [];
        $date = date('Y/m/d');
        $group = $args['group'];
        $className = $args['className'];
        $baseTpl = <<<doc
<?php
/**
 * quick_curd
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: $date
 * 描述:
 */

use think\\facade\\Route;


Route::group('$group', function () {    
doc;
    $baseTpl .= <<<doc

  Route::get('index', "app\admin\controller\auto\\$className@index");
doc;
    if (in_array('list', $admin_apis)) {
        $baseTpl .= <<<doc

  Route::get('list_config', "app\admin\controller\auto\\$className@list_config");
  Route::get('list', "app\admin\controller\auto\\$className@list");
doc;
    }
    if (in_array('get', $admin_apis)) {
        $baseTpl .= <<<doc

  Route::get('get', "app\admin\controller\auto\\$className@get");
doc;
    }
    if (in_array('save_data', $admin_apis) || in_array('edit_data', $admin_apis)) {
        $baseTpl .= <<<doc

  Route::rule('save', "app\admin\controller\auto\\$className@save_data", 'POST|PUT');
doc;
    }
    if (in_array('del_data', $admin_apis)) {
        $baseTpl .= <<<doc

  Route::delete('delete', "app\admin\controller\auto\\$className@del_data");
doc;
    }
    if (in_array('list_options', $admin_apis)) {
        $baseTpl .= <<<doc

  Route::get('list_options', "app\admin\controller\auto\\$className@list_options");
doc;
    }
    if (in_array('status', $admin_apis)) {
        $baseTpl .= <<<doc

  Route::put('status', "app\admin\controller\auto\\$className@status");
doc;
    }

    $baseTpl .= <<<doc

})->middleware([app\middleware\AuthCheck::class, 'think\middleware\SessionInit']);
doc;
        return $baseTpl;
    }


    // 生成前台控制器
    public static function tpl_front_controller($args): string
    {
        $date = date('Y/m/d');
        $className = $args['className'];
        $resultName = $args['resultName'];
        $apis = $args['apis'] ?? [];
        $need_login = $args['need_login'] ?? false;
        $need_user_id = $args['need_user_id'] ?? false;
        $baseTpl = <<<doc
<?php
/**
 * quick_curd
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: $date
 * 描述:
 */

namespace app\\index\\controller\\auto;

use app\\index\\controller\\BaseIndex;
use think\\App;
use app\\result\\auto\\$resultName;

class $className extends BaseIndex
{

doc;
        //无需登录
        if (!$need_login){
            $baseTpl.=<<<doc

    protected \$unauthorized = ['*'];
doc;
        }
        $baseTpl .= <<<doc

    public function __construct(App \$app)
    {
        parent::__construct(\$app);
        \$this->objResult = new $resultName();
    }
doc;

        if (in_array('list', $apis)) {
            $baseTpl .= <<<doc


    //数据列表
    public function list()
    {
        data_exit_json(\$this->objResult->api_list(\$this->param));
    }
doc;
        }

        if (in_array('detail', $apis)) {
            $baseTpl .= <<<doc


    //获取详情
    public function detail()
    {
        data_exit_json(\$this->objResult->api_get(\$this->param));
    }
doc;
        }

        if (in_array('action', $apis)) {
            $baseTpl .= <<<doc


    //保存数据
    public function action()
    {
        data_exit_json(\$this->objResult->api_save_data(\$this->param));
    }
doc;
        }

        if (in_array('remove', $apis)) {
            $baseTpl .= <<<doc


    //删除数据
    public function delete()
    {
        data_exit_json(\$this->objResult->api_delete(\$this->param));
    }
doc;
        }

        if (in_array('setDefault', $apis)) {
            $baseTpl .= <<<doc


    //设置默认
    public function default()
    {
        data_exit_json(\$this->objResult->api_set_default(\$this->param));
    }
doc;
        }

        if (in_array('list_options', $apis)) {
            $baseTpl .= <<<doc


    //获取下拉列表
    public function list_options()
    {
        data_exit_json(\$this->objResult->api_list_options(\$this->param));
    }
doc;
        }


        $baseTpl .= <<<doc

}
doc;
        return $baseTpl;
    }

    // 生成前台路由
    public static function tpl_front_route($args): string
    {
        $apis = $args['apis'] ?? [];
        $date = date('Y/m/d');
        $group = $args['group'];
        $className = $args['className'];
        $baseTpl = <<<doc
<?php
/**
 * quick_curd
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: $date
 * 描述:
 */

use think\\facade\\Route;


Route::group('$group', function () {
doc;
    if (in_array('list', $apis)) {
        $baseTpl .= <<<doc

  Route::get('list', "app\index\controller\auto\\$className@list");
doc;
    }

    if (in_array('detail', $apis)) {
        $baseTpl .= <<<doc

  Route::get('detail', "app\index\controller\auto\\$className@detail");
doc;
    }

    if (in_array('action', $apis)) {
        $baseTpl .= <<<doc

  Route::post('action', "app\index\controller\auto\\$className@action");
doc;
    }

    if (in_array('remove', $apis)) {
        $baseTpl .= <<<doc

  Route::delete('remove', "app\index\controller\auto\\$className@delete");
doc;
    }

    if (in_array('setDefault', $apis)) {
        $baseTpl .= <<<doc

  Route::put('setDefault', "app\index\controller\auto\\$className@default");
doc;
    }

    if (in_array('list_options', $apis)) {
        $baseTpl .= <<<doc

  Route::get('list_options', "app\index\controller\auto\\$className@list_options");
doc;
    }

    $baseTpl .= <<<doc

});
doc;
        return $baseTpl;
    }

}
